package com.hcc.flow.server.service.flowTask;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.hcc.flow.server.common.advice.RRException;
import com.hcc.flow.server.common.enums.CheckStatusType;
import com.hcc.flow.server.common.enums.MsgType;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.utils.CommUtil;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.dao.flowDesign.FlowTaskTypeDao;
import com.hcc.flow.server.dao.flowTask.AdContentDao;
import com.hcc.flow.server.dao.sys.OrgDao;
import com.hcc.flow.server.dto.workbench.MsgNoticeDto;
import com.hcc.flow.server.model.common.LoginUser;
import com.hcc.flow.server.model.flowDesign.FlowTaskType;
import com.hcc.flow.server.model.flowTask.AdContent;
import com.hcc.flow.server.model.sys.Org;
import com.hcc.flow.server.model.sys.SysAuditLogs;
import com.hcc.flow.server.model.sys.SysUser;
import com.hcc.flow.server.service.sys.SysLogService;
import com.hcc.flow.server.service.workbench.MsgNoticeService;
import com.hcc.flow.server.utils.UserUtil;
import com.hcc.flow.server.vo.flowTask.AdContentVO;


@Service
public class AdContentService {

	@Autowired
	private AdContentDao adContentDao;
	@Autowired
	private SysLogService logService;
	@Autowired
	private MsgNoticeService msgNoticeService;
	@Autowired
	private OrgDao orgDao;
	@Autowired
	private FlowTaskTypeDao flowTaskTypeDao;
	
	@Transactional
	public ApiResult<?> save(List<AdContent> adContents) {
		if(CollectionUtils.isEmpty(adContents)){
			return ApiResult.error("要保存的素材数据不能为空");
		}
		if (adContents.parallelStream().filter(p->p.getAdTypeId() == null).count() > 0 ) {
			throw new RRException("保存的素材的类型id不能为空");
		}
		if (adContents.parallelStream().filter(p->(p.getAdTypeId() == 6 && StringUtilsV2.isBlank(p.getAdContent()))).count() > 0 ) {
			throw new RRException("保存流媒体类型的素材，流媒体地址不能为空");
		}
		if (adContents.parallelStream().filter(p->(p.getAdTypeId() == 4 || p.getAdTypeId() == 5 || p.getAdTypeId() == 8) && StringUtilsV2.isBlank(p.getAdContent())).count() > 0 ) {
			throw new RRException("保存文本类型的素材，文本内容不能为空");
		}
		SysUser loginUser = UserUtil.getLoginUser();
		List<String> isWaitAuditedIds = new ArrayList<>();
		for (AdContent adContent : adContents) {
			Integer adTypeId = adContent.getAdTypeId();
			if (adTypeId == 3) {
				if (StringUtilsV2.isBlank(adContent.getMd5())) {
					adContent.setMd5(DigestUtils.md5Hex(adContent.getAdContent()));
				}
				if (adContent.getAdSize() == null || adContent.getAdSize() == 0) {
					adContent.setAdSize(adContent.getAdContent().getBytes().length);
				}
			}
			AdContent localAdContent = adContentDao.getByPara(adContent.getMd5(), loginUser.getOrgId(), adContent.getAdName());
			if(localAdContent != null && (adTypeId == 3)) {
				localAdContent = null;
			}
			if(localAdContent == null) {
				adContent.setCreateUserId(loginUser.getUserId());
				adContent.setCreateOrgId(loginUser.getOrgId());
				if(adContent.getStatus() == null || CheckStatusType.SUBMIT.getCode().equals(adContent.getStatus())){
					adContent.setStatus(CheckStatusType.SUBMIT.getCode());
					adContentDao.save(adContent);
				}else if(CheckStatusType.WAIT_AUDITED.getCode().equals(adContent.getStatus())){
					adContent.setSubmitterId(loginUser.getUserId());
					adContentDao.save(adContent);
					isWaitAuditedIds.add(adContent.getAdId());
				}
				logService.saveAuditLogs(new SysAuditLogs(loginUser.getUserId(), new Date(),"素材-保存(入库)", adContent.getAdId()));
			}else {
				localAdContent.setCreateTime(new Date());
				localAdContent.setAdUrl(adContent.getAdUrl());
				if(CheckStatusType.REFUSED.getCode().equals(localAdContent.getStatus())){//本地数据库相同素材已驳回时
					if(adContent.getStatus() == null){
						localAdContent.setStatus(CheckStatusType.SUBMIT.getCode());
					}else if(CheckStatusType.WAIT_AUDITED.getCode().equals(adContent.getStatus())){
						localAdContent.setSubmitterId(loginUser.getUserId());
						isWaitAuditedIds.add(localAdContent.getAdId());
					}
				}
				adContentDao.update(localAdContent);
				logService.saveAuditLogs(new SysAuditLogs(loginUser.getUserId(), new Date(),"相同素材再次上传保存(入库)", localAdContent.getAdId()));
			}
		}
		if(isWaitAuditedIds.size() > 0){
			return submit(isWaitAuditedIds);
		}
		return ApiResult.ok();
	}
	
	@Transactional
	public ApiResult<?> submit(List<String> ids){
		if (CollectionUtils.isEmpty(ids)) {
			return ApiResult.error("ids不能为空");
		}
		String msg = "素材-提交(初)审";
		if (ids.size() > 1) {
			msg = "素材-批量提交(初)审";
		}
		LoginUser user = UserUtil.getLoginUser();
		Org org = orgDao.getById(user.getOrgId());
		if(org == null){
			return ApiResult.error("未找到登录用户机构信息");
		}
		String ownAudit = "1";//自有审核模式: 0单一审核模式 1工作流审核模式
		if(StringUtilsV2.isBlank(ownAudit)){
			return ApiResult.error("登录用户机构自有审核模式未设置");
		}
		adContentDao.updateStatus(ids, CheckStatusType.WAIT_AUDITED.getCode(),user.getUserId());
		MsgNoticeDto notice;
		StringBuffer sb;
		ApiResult<?> apiResult = null;
		AdContentVO taskModel;
		Date now = CommUtil.getDateJJSecond(new Date(),1);
		FlowTaskType flowTaskType= flowTaskTypeDao.getByModel(AdContent.class.getSimpleName());
		if(flowTaskType == null){
			return ApiResult.error("通过类型实体名("+AdContent.class.getSimpleName()+")未找到对应流程业务类型");
		}
		for(String id : ids) {
			taskModel = adContentDao.getById(id);
			if (taskModel == null){
				return ApiResult.error("要审核的素材为空");
			}
			sb = new StringBuffer()
					.append("需要(初)审的素材ID: ").append(taskModel.getIndexId()).append(",<br/>")
					.append("素材类型: ").append(taskModel.getAdTypeName()).append(",<br/>")
					.append("素材名称: ").append(taskModel.getAdName());
			if("1".equals(ownAudit)){
				notice = new MsgNoticeDto();
				notice.setType(MsgType.TASK.getCode());
				notice.setTaskType(flowTaskType.getTaskTypeId().toString());
				notice.setTitle("素材待(初)审通知");
				notice.setContent(sb.toString());
				notice.setFlowFromId(id);
				notice.setFlowVerifyStatus(CheckStatusType.WAIT_AUDITED.getCode());
				notice.setFlowVerifyReason("提交素材(初)审流程");
				notice.setFlowSubmitNo(String.valueOf(System.currentTimeMillis()));
				apiResult = msgNoticeService.save(notice);
				if(!apiResult.isSuccess()){
					throw new RRException(apiResult.getMsg());
				}
			}
			logService.saveAuditLogs(new SysAuditLogs(UserUtil.getLoginUser().getUserId(), now,msg+(apiResult!=null?apiResult.getData():""), id));
		}
		return ApiResult.ok();
	}

	
	@Transactional
	public ApiResult<?> delete(String id) {
		AdContent adContent = adContentDao.getById(id);
		if(adContent == null){
			return ApiResult.error("要删除的素材不存在");
		}
		AdContentVO taskModel = adContentDao.getById(id);
		if (taskModel == null){
			return ApiResult.error("要审核的素材为空");
		}
		FlowTaskType flowTaskType= flowTaskTypeDao.getByModel(AdContent.class.getSimpleName());
		if(flowTaskType == null){
			return ApiResult.error("通过类型实体名("+AdContent.class.getSimpleName()+")未找到对应流程业务类型");
		}
		MsgNoticeDto notice = new MsgNoticeDto();
		notice.setType(MsgType.RESULT.getCode());
		notice.setTaskType(flowTaskType.getTaskTypeId().toString());
		notice.setTitle("素材被删除通知");
		notice.setCollectUserIds(Arrays.asList(adContent.getSubmitterId(),adContent.getCreateUserId()));//接收人
		StringBuffer sb = new StringBuffer().append("您录入/提交的素材已被删除,<br/>")
				.append("素材ID: ").append(taskModel.getIndexId()).append(",<br/>")
				.append("素材类型: ").append(taskModel.getAdTypeName()).append(",<br/>")
				.append("素材名称: ").append(taskModel.getAdName());
		notice.setContent(sb.toString());
		notice.setFlowFromId(id);
		notice.setFlowVerifyStatus(CheckStatusType.DELETE.getCode());
		notice.setFlowVerifyReason("素材被删除");
		ApiResult<?> apiResult = msgNoticeService.save(notice);
		if(!apiResult.isSuccess()){
			throw new RRException(apiResult.getMsg());
		}
		adContentDao.deletes(Arrays.asList(id));
		logService.saveAuditLogs(new SysAuditLogs(UserUtil.getLoginUser().getUserId(), new Date(),"素材-逻辑删除", id));
		return apiResult;
	}

	
}
